package logic

import (
	"context"
	"fmt"
	"math/rand"
	"shopconnect/model/redis"
	"time"

	"shopconnect/shoprpc/internal/svc"
	"shopconnect/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *shoprpc.SendSmsRequest) (*shoprpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get("sendSmsNumMinute" + in.Source + in.Mobile)
	if get.Val() != "" {
		return nil, fmt.Errorf("一分钟只能发一次")
	}
	code := rand.Intn(9000) + 1000
	//sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return nil, fmt.Errorf("短信发送失败")
	//}
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}
	redis.Rdb.Set("sendSms"+in.Source+in.Mobile, code, time.Minute*5)
	incr := redis.Rdb.Incr("sendSmsNum" + in.Source + in.Mobile)
	if incr.Val() > 1 {
		redis.Rdb.Set("sendSmsNumMinute"+in.Source+in.Mobile, "1", time.Minute*1)
		redis.Rdb.Del("sendSmsNum" + in.Source + in.Mobile)
	}
	return &shoprpc.SendSmsResponse{}, nil
}
